package com.ego.product.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: ego
 * @description: Feign远程调用配置
 * @author: KamTang
 * @create: 2022-12-21 09:01
 **/
@Configuration
public class FeignConfig {

    /**
     * TODO 远程调用可能会把网站发的请求中的cookie信息清空，所以需要保存老请求的cookie信息。
     */
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // RequestContextHolder拿到刚进来的这个请求
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                // 老请求
                HttpServletRequest request = requestAttributes.getRequest();

                // 同步请求数据Cookie
                String cookie = request.getHeader("Cookie");
                // 给新请求同步了老请求的cookie
                requestTemplate.header("Cookie", cookie);
            }
        };
    }

}
